package com.frxuexi.repair.view

import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.LEFT
import androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.frxuexi.lib_base.entity.RepairBeanItem
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.RequestType
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.repair.adapter.RepairAdapter
import com.frxuexi.repair.RepairIntent
import com.frxuexi.repair.RepairViewModel
import com.frxuexi.repair.databinding.ActivityRepairBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = "/repair/RepairActivity")
@AndroidEntryPoint
class RepairActivity : BaseActivity<ActivityRepairBinding, RepairIntent, RepairViewModel>() {
    override val binding: ActivityRepairBinding by lazy { ActivityRepairBinding.inflate(layoutInflater) }
    override val vm: RepairViewModel by viewModels<RepairViewModel>()
    val repairAdapter by lazy { RepairAdapter() }
    var flag=false//降序
    var list = mutableListOf<RepairBeanItem>()
    var type=""
    var position=0
    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*>->{
                        when(it.type){
                            RequestType.REPIRITM->{
                                repairAdapter.data.clear()
                                val items = it.data as RepairBeanItem
                                repairAdapter.addData(items)
                                repairAdapter.notifyDataSetChanged()
                            }
                            RequestType.DEFAULT->{
                                repairAdapter.data.clear()
                                list.clear()
                                val items = it.data as Collection<RepairBeanItem>
                                list.addAll(items)
                                Log.i("lr",items.toString())
                                repairAdapter.addData(items)
                                repairAdapter.notifyDataSetChanged()
                            }
                            RequestType.DELETE->{
                                val b = it.data as String
                                val value = b.split(",")[0].toBoolean()
                                if(value) {
                                    repairAdapter.notifyItemRemoved(position)
                                }
                            }

                            else -> {}
                        }

                    }
                    is UiState.onError->{
                        Log.i("lr",it.msg)
                    }
                    else->{}
                }
            }
        }
    }

    override fun initView() {
        binding.headRepair.apply {
            headBack.setOnClickListener {
                finish()
            }
            headTitle.setText("维修管理")
            headAdd.setOnClickListener {
                ARouter.getInstance().build("/repair/RepairAddActivity").navigation()
            }
        }

        binding.rvRepair.apply {
            adapter=repairAdapter
            layoutManager=LinearLayoutManager(this@RepairActivity)
        }

        repairAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/repair/RepairApproveActivity")
//                .withSerializable("repair",repairAdapter.data.get(position))
                .withString("rid",repairAdapter.data.get(position).id.toString())
                .navigation()
        }


        binding.repairOrder.setOnClickListener {
            if(flag){//升序
                repairAdapter.data.sortBy { it.repairTime }
                binding.repairOrderiv.setImageResource(com.frxuexi.lib_base.R.drawable.ic_action_asc)
            }else{//降序
                repairAdapter.data.sortByDescending { it.repairTime }
                binding.repairOrderiv.setImageResource(com.frxuexi.lib_base.R.drawable.ic_action_down)
            }
            repairAdapter.notifyDataSetChanged()
            flag=!flag
        }

        binding.btnSearch.setOnClickListener {
            val content = binding.repairSv.text.toString()
            if(type.isEmpty()){
                vm.sendIntent(RepairIntent.getRepairByNum(content))
            }else{
                vm.sendIntent(RepairIntent.getRepairByUser(content))
            }

        }

        binding.repairSv.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if(s.isNullOrEmpty()){
                    repairAdapter.data.clear()
                    repairAdapter.addData(list)
                    repairAdapter.notifyDataSetChanged()
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })

        binding.repairFilter.setOnClickListener {
            type="user"
        }

        ItemTouchHelper(object :SimpleCallback(LEFT, LEFT){
            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return false
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                position = viewHolder.adapterPosition
                vm.sendIntent(RepairIntent.deleteRepair(repairAdapter.data.get(position).id!!))

            }

        }).attachToRecyclerView(binding.rvRepair)
    }

    override fun onResume() {
        super.onResume()
        vm.sendIntent(RepairIntent.getRepairs)
    }

}